package com.example.hcd;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.example.hcd.datamanage.RoleInfoData;
import com.example.hcd.datamanage.UserInfo;
import com.example.hcd.functionactivity.BaseActivity;
import com.example.hcd.internet.InternetKeep;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.Constants;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.ToastHelp;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

public class LoginActivity extends BaseActivity implements OnClickListener {
    private EditText mUserName;
    private EditText mPassWord;
    private LoadUserInfo UserInfoLoad;
    private LoginActivity context;
    private SharedPreferences mySharedPreferences;
    private Intent mIntent;
//    private JPushMessage mNotification = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mPageName = "LoginActivity";
        setContentView(R.layout.login_view);
        context = this;
        mIntent = getIntent();

        mUserName = (EditText) findViewById(R.id.login_user);
        mySharedPreferences = getSharedPreferences("niciname",
                Activity.MODE_PRIVATE);
        String name = mySharedPreferences.getString("name", "");
        mUserName.setText(name);

        mPassWord = (EditText) findViewById(R.id.login_password);
        String password = mySharedPreferences.getString("password", "");
        mPassWord.setText(password);

        findViewById(R.id.login_btn).setOnClickListener(this);

        //检测系统版本
        //UpdateManager manager = new UpdateManager(context);
        // 检查软件更新
        //manager.checkUpdate();

//		//透明状态栏
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        //透明导航栏
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);


//        mNotification = (JPushMessage) getIntent().getSerializableExtra(Constants.NOTIFICATION);

    }

    private boolean checkPasswordAndUsername(String password, String username) {
        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) {
            //Toast.makeText(this, "用户名或者密码不能为空", Toast.LENGTH_SHORT).show();
            ToastHelp.doToastInTop(this, "用户名或者密码不能为空");
            return false;
        }

        //实例化SharedPreferences.Editor对象（第二步）
        SharedPreferences.Editor editor = mySharedPreferences.edit();
        editor.putString("name", username);
        editor.putString("password", password);
        //提交当前数据
        editor.commit();


        return true;
    }

    private class LoadUserInfo extends AsyncTask<String, Integer, String> {

        private final String CODE = "code";
        private DefaultHttpClient mHttpClient;
        private MyLoadingDialog myDialog;

        @Override
        protected void onPreExecute() {

            mHttpClient = new DefaultHttpClient();
            myDialog = new MyLoadingDialog(LoginActivity.this, mHttpClient, "登入中...", false);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            HttpResponse response = null;
            BufferedReader reader = null;
            try {

                ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
                vs.add(new BasicNameValuePair("username", params[0]));
                vs.add(new BasicNameValuePair("password", params[1]));
                vs.add(new BasicNameValuePair("registrationid", params[2]));
//                Log.e("test",params[2]+"");
                response = LinkHelp.post(URLS.getLogin(), vs, false);

                if (response != null) {
                    StatusLine line = response.getStatusLine();
                    if (line.getStatusCode() == 200) {
                        reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                        StringBuilder sb = new StringBuilder();
                        for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                            sb.append(s);
                        }
                        reader.close();
                        result = sb.toString();

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            myDialog.dimiss();
            if (myDialog.mCancel) {
                return;
            }
            int errorId = -1;
            if (TextUtils.isEmpty(result)) {
                errorId = R.string.dialog_load_fail_network;

                ToastHelp.doToast(LoginActivity.this, "网络异常");

            } else {
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(result);
                    if (jsonObject.isNull(CODE)) {
                        String status = jsonObject.getString("status");
                        UserInfo info = UserInfo.getUserInfor();
                        if (status.equals("success")) {
//                            Toast.makeText(LoginActivity.this, "登录成功,加载用户信息", Toast.LENGTH_SHORT).show();

                            //加载用户信息
                            {
                                JSONObject useobject = jsonObject.getJSONObject("userObject");
                                String id = useobject.getString("id");
                                String name = useobject.getString("name");
                                info.setId(id);
                                info.setDepartmnet(useobject.isNull("QQ") ? "" : useobject.getString("department"));
                                info.setName(name);
                                info.setBirthday(useobject.isNull("birthday") ? "" : useobject.getString("birthday"));
                                info.setZip_code(useobject.isNull("zip_code") ? "" : useobject.getString("zip_code"));
                                info.setLastModifyPdTime(useobject.isNull("lastModifyPdTime") ? null : useobject.getString("lastModifyPdTime"));
                                info.setIsHead(useobject.isNull("isHead") ? "" : useobject.getString("isHead"));
                                info.setHome_tel(useobject.isNull("home_tel") ? "" : useobject.getString("home_tel"));
                                info.setOffice_fax(useobject.isNull("office_fax") ? "" : useobject.getString("office_fax"));
                                info.setEmail(useobject.isNull("emailAddress") ? "" : useobject.getString("emailAddress"));
                                info.setOffice_tel(useobject.isNull("officeTel") ? "" : useobject.getString("officeTel"));
                                info.setCompanyName(useobject.isNull("companyName") ? "" : useobject.getString("companyName"));
                                info.setPassword(useobject.isNull("passWord") ? "" : useobject.getString("passWord"));
                                info.setHome_address(useobject.isNull("home_address") ? "" : useobject.getString("home_address"));
                                info.setQq(useobject.isNull("QQ") ? "" : useobject.getString("QQ"));
                                info.setUsername(useobject.isNull("userName") ? "" : useobject.getString("userName"));
                                info.setGender(useobject.getInt("gender"));
                                info.setDepartmentId(useobject.isNull("departmentId") ? "" : useobject.getString("departmentId"));
                                info.setCompanyId(useobject.isNull("companyId") ? "" : useobject.getString("companyId"));
                                info.setMobileNumber(useobject.isNull("mobileNumber") ? "" : useobject.getString("mobileNumber"));
                                info.setIsLogin(true);
                                JSONArray roleArray = useobject.getJSONArray("authorities");
                                for (int i = 0; i < roleArray.length(); i++) {
                                    JSONObject obj = roleArray.getJSONObject(i);
                                    RoleInfoData data = new RoleInfoData();

                                    data.setId(obj.getString("id"));
                                    data.setRoleName(obj.getString("roleName"));
                                    data.setRole_code(obj.getString("role_code"));
                                    info.getRoleInfoDatas().add(data);
                                }

                            }
                            // 登录完成jpush注册
                            if (!info.getDepartmnet().equals("洗车部")) {
                                Set<String> sets = new HashSet<>();
                                sets.add("c_android");
                                sets.add("c");
                                sets.add(info.getDepartmentId());
                                sets.add(info.getUserRolesid());
                                JPushInterface.setAliasAndTags(VenadaOAApplication.getInstance(), info.getId().replaceAll("-", "_"), sets);
                            }

                            //加载系统信息

//                    		InternetKeep.getInstence().getSystemInfo(context);
//                            LoadSyetemInfo system = new LoadSyetemInfo();
//                            system.execute();

//                           if (InternetKeep.getInstence().isSystemInfoLoad){
                            Intent intent = new Intent(LoginActivity.this, MenuActivity.class);
                            if (null != mIntent && mIntent.hasExtra(Constants.NOTIFICATION)) {
                                intent.putExtra(Constants.NOTIFICATION, mIntent.getSerializableExtra(Constants.NOTIFICATION));
                                mIntent = null;

                            }
                            startActivity(intent);
//                            }else
//						   {
//							   LoadSyetemInfo system = new LoadSyetemInfo();
//                               system.execute();
//						   }

                            return;
                        } else if (status.equals("error")) {
                            String msg = jsonObject.getString("msg");
                            //Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                            ToastHelp.doToastInTop(LoginActivity.this, msg);
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    private class LoadSyetemInfo extends AsyncTask<String, Integer, String> {


        HttpResponse response = null;
        BufferedReader reader = null;
        MyLoadingDialog myDialog;

        @Override
        protected void onPreExecute() {
            myDialog = new MyLoadingDialog(LoginActivity.this, null, "系统信息加载中..", false);

        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try {

                response = LinkHelp.post(URLS.getSystemInfo(), null, true);


                if (response != null) {
                    StatusLine line = response.getStatusLine();
                    if (line.getStatusCode() == 200) {
                        reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                        StringBuilder sb = new StringBuilder();
                        for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                            sb.append(s);
                        }
                        result = sb.toString();


                    }
                }
            } catch (Exception e) {

            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            //myDialog.dimiss();
            if (!TextUtils.isEmpty(result)) {

                if (result.contains("error")) {

                    JSONObject jsonObject;
                    try {
                        jsonObject = new JSONObject(result);
                        String msg = jsonObject.getString("msg");
                        ToastHelp.doToastInTop(LoginActivity.this, msg);
                        InternetKeep.getInstence().isSystemInfoLoad = false;
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                } else {
//					 Toast.makeText(LoginActivity.this, "获取系统信息成功",
//					 Toast.LENGTH_SHORT).show();
                    try {
                        InternetKeep.getInstence().ParseSystemInfo(result);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    InternetKeep.getInstence().isSystemInfoLoad = true;
                    mPassWord.setText("");

                    Intent intent = new Intent(LoginActivity.this, MenuActivity.class);
                    startActivity(intent);

                    myDialog.dimiss();
                }

            } else {
                ToastHelp.doToastInTop(LoginActivity.this, "获取系统信息失败");
                InternetKeep.getInstence().isSystemInfoLoad = false;
                myDialog.dimiss();
            }
        }

    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        int tag = arg0.getId();
        switch (tag) {
            case R.id.login_btn:

                if (checkPasswordAndUsername(mPassWord.getText().toString(), mUserName.getText().toString())) {

                    //Toast.makeText(LoginActivity.this, "开始登录", Toast.LENGTH_SHORT).show();
                    UserInfoLoad = new LoadUserInfo();
                    UserInfoLoad.execute(mUserName.getText().toString(), mPassWord.getText().toString(), JPushInterface.getRegistrationID(VenadaOAApplication.getInstance()));

                }
                break;

            default:
                break;
        }

    }


}
